package service;

import common.Message;
import entity.Chat;
import entity.User;
import service.ChatService;
import service.UserService;
import view.ServerView;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

/**
 * 服务器与客户端通信线程
 */
public class ServerThread extends Thread {

    private Socket client;
    private volatile boolean isRunning;
    private ObjectInputStream input;
    private ObjectOutputStream output;
    private User user;

    public ServerThread(Socket client) {
        this.client = client;
        this.isRunning = true;
    }

    public void myStop() {
        this.isRunning = false;
    }

    public void send(Message message) {
        try {
            output = new ObjectOutputStream(client.getOutputStream());
            output.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (isRunning) {
                input = new ObjectInputStream(client.getInputStream());
                Message msg = (Message) input.readObject();
                //判断消息类型
                switch (msg.getType()) {
                    case GET_FRIENDS:// 获取好友列表
                        User user = (User) msg.getContent();
                        new UserService().getFriends(user.getQq());
                        break;
                    case CHAT_MESSAGE:// 普通聊天信息
                        Chat chat = (Chat) msg.getContent();
                        new ChatService().receiveChat(chat);
                        break;
                    case GET_CHAT_LIST:// 获取聊天记录
                        ArrayList<User> content = (ArrayList<User>) msg.getContent();
                        User user1 = content.get(0);
                        User friend = content.get(1);
                        new ChatService().getChatList(user1.getQq(), friend.getQq());
                        break;
                    case OFFLINE:// 用户下线
                        User offlineUser = (User) msg.getContent();
                        new UserService().userOffline(offlineUser);
                        break;
                    default:
                        System.out.println("未知类型");
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
